/*
 * @Descripttion: ConnectedRouter组件，用于派发路由动作到redux中
 * @Author: lukasavage
 * @Date: 2021-11-29 21:01:24
 * @LastEditors: lukasavage
 * @LastEditTime: 2021-11-29 21:23:50
 */

/**
 * 这个组件用来替代我们原来的Router容器组件，负责监听路径变化，然后派发动作
 */
import React, { Component } from 'react';
import { reactReduxContext } from '../react-redux'
import { onLocationChange } from './actions'
import { Router } from '../react-router'

export default class ConnectedRouter extends Component {
    static contextType = reactReduxContext;
    constructor(props, context) {
        super(props);
        // 当路径发生变化后，会地哦啊哟好难过回调函数，传入最新的location和action
        this.unlisten = this.props.history.listen((location, action) => { 
            context.store.dispatch(onLocationChange(location, action));
        })
    }
    componentWillUnmount() {
        this.unlisten();
    }
    render() {
        return (
            <Router history={ this.props.history }>
                { this.props.children }
            </Router>
        )
    }
}

